package com.tanhua.manage.service;

import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tanhua.manage.domain.Admin;
import com.tanhua.manage.exception.BusinessException;
import com.tanhua.manage.mapper.AdminMapper;
import com.tanhua.manage.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class AdminService extends ServiceImpl<AdminMapper, Admin> {

    private static final String CACHE_KEY_CAP_PREFIX = "MANAGE_CAP_";
    public static final String CACHE_KEY_TOKEN_PREFIX="MANAGE_TOKEN_";//token前缀

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private JwtUtils jwtUtils;

    /**
     * 保存生成的验证码
     * @param uuid
     * @param code
     */
    public void saveCode(String uuid, String code) {
        String key = CACHE_KEY_CAP_PREFIX + uuid;//key=MANAGE_CAP_+uuid(前端生成传入的)
        // 缓存验证码，10分钟后失效
        redisTemplate.opsForValue().set(key,code, Duration.ofMinutes(10));
        //redisTemplate.opsForValue().set(key,code, 10,TimeUnit.MINUTES);
    }

    /**
     * 获取登陆用户信息
     * @return
     */
    public Admin getByToken(String authorization) {
        String token = authorization.replaceFirst("Bearer ","");
        String tokenKey = CACHE_KEY_TOKEN_PREFIX + token;
        String adminString = (String) redisTemplate.opsForValue().get(tokenKey);
        Admin admin = null;
        if(StringUtils.isNotEmpty(adminString)) {
            admin = JSON.parseObject(adminString, Admin.class);
            // 延长有效期 30分钟
            redisTemplate.expire(tokenKey,30, TimeUnit.MINUTES);
        }
        return admin;
    }

    /**
     * 登录
     */
    public String login(String username, String password, String verificationCode, String uuid) {
        //a.根据MANAGE_CAP_+uuid从redis查询验证码
        String key = CACHE_KEY_CAP_PREFIX + uuid;
        String redisCode = (String)redisTemplate.opsForValue().get(key);
        //b.根据redis中验证码 和  登录输入的验证码 对比
        if(StringUtils.isEmpty(redisCode) || !redisCode.equals(verificationCode)){
            throw new BusinessException("验证码错误");
        }
        //c.跟username查询tb_admin表 用户是否存在
        Admin admin = this.query().eq("username", username).one();
        if(admin == null ){
            throw new BusinessException("用户不存在");
        }
        //d.获取数据库密码 跟 用户传入的密码 对比
        if(!admin.getPassword().equals(SecureUtil.md5(password))){
            throw new BusinessException("用户密码错误");
        }
        //e.生成token存入redis
        String token = jwtUtils.createJWT(admin.getUsername(), admin.getId());
        String tokenKey = CACHE_KEY_TOKEN_PREFIX+token;//token key
        String adminStr = JSON.toJSONString(admin);//将amdin对象转为admin字符串
        redisTemplate.opsForValue().set(tokenKey,adminStr,1,TimeUnit.HOURS);
        //f.将生成的token返回给页面
        return token;
    }


    //退出登录
    public ResponseEntity logout(String token) {
        String key = CACHE_KEY_TOKEN_PREFIX+token;
        redisTemplate.delete(key);
        return ResponseEntity.ok(null);
    }
}
